package Demo1;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-09-05
 * Time: 10:03
 */



public class Test {
    static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public static ListNode head;

    public static void makeList(){
        ListNode node4 = new ListNode(4);
        ListNode node3 = new ListNode(3,node4);
        ListNode node2 = new ListNode(2,node3);
        ListNode node1 = new ListNode(1,node2);
        head = node1;
    }

    //两两交换链表中的节点
    public ListNode swapPairs(ListNode head) {
        //保证链表最少有两个节点
        if(head == null || head.next == null) return head;
        //定义三个指针
        ListNode prev = head;
        ListNode cur = prev.next;
        ListNode curN = cur.next;
        ListNode jump = head;
        boolean flag = true;
        while(cur != null){
            cur.next = prev;
            prev.next = curN;
            if(flag){
                this.head = cur;
                flag = false;
            }
            //保证了至少还有两个节点
            if(curN == null || curN.next == null) return head;
            prev = curN;
            cur = curN.next;
            curN = cur.next;
            //连接两两节点之间关系
            jump.next = cur;
            jump = prev;
        }
        return head;
    }
    public static void main(String[] args) {
        Test t = new Test();
        makeList();
        t.swapPairs(head);
        ListNode cur = head;
        while(cur != null){
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
    }
}
